package com.atme.micromall.points.util;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * redis锁
 * id作为key
 */
@Component
public class RedisLock {

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    //加锁
    public boolean lock(String id,String value){
        //setIfAbsent相当于jedis中的setnx，如果能赋值就返回true，如果已经有值了，就返回false
        //即：在判断这个key是不是第一次进入这个方法
        boolean flog=redisTemplate.opsForValue().setIfAbsent(id,value);
        if (flog){
            redisTemplate.expire(id,5, TimeUnit.SECONDS);
            System.out.println("设置锁时间");
        }
        return flog;
    }

    //解锁
    public void unlock(String key){
        System.out.println("解锁");
        redisTemplate.delete(key);
    }
}
